import json
import traceback

import pymysql

#  多个 sn 以逗号,隔开 如： 1234,5678,0912
#  请输入订单号
#  只需要输入订单号就可以实现 在线支付
from django.forms import model_to_dict


def _checkParams(orderSn):
    if orderSn:
        return True
    else:
        return False


def _getOrderItemList(cursor, orderId):
    selectOrderItemsSql = f"""
    SELECT
	order_id orderId,
	item_id itemId,
	item_name itemName,
	count count,
	price price,
	discount_price discountPrice,
	residue_price residuePrice,
	final_price finalPrice,
	final_count finalCount,
	final_status finalStatus,
	STATUS `status`
FROM
	mall_order.order_item
WHERE
	order_id = {orderId}
    """
    cursor.execute(selectOrderItemsSql)
    items = cursor.fetchall()
    ois = []
    for item in items:
        oi = OrderItem(item[0], item[1], item[2], item[3], item[4], item[5], item[6], item[7], item[8], item[9],
                       item[10])
        ois.append(oi.__dict__)
    return ois


def _getOrderItemDiscountList(cursor, orderId):
    selectOrderItemDiscountsSql = f"""
        SELECT
            oi.order_id               orderId,
            oi.count                  orderCount,
            IFNULL(oi.final_count, 0) deliveryCount,
            (10 + oid.type)           discountType,
            oid.item_id               itemId,
            oid.coupon_id             discountId,
            oid.discount_fee          shareDiscountAmount,
            2                         costHolder
        FROM
            mall_order.order_item_discount oid
            LEFT JOIN mall_order.order_item oi ON oid.item_id = oi.item_id
        WHERE
            oi.order_id = {orderId}
        UNION
        SELECT
            oi.order_id               orderId,
            oi.count                  orderCount,
            IFNULL(oi.final_count, 0) deliveryCount,
            (20 + oic.coupon_type)    discountType,
            oic.item_id               itemId,
            oic.coupon_id             discountId,
            oic.coupon_fee            shareDiscountAmount,
            oic.cost_holder           costHolder
        FROM
            mall_order.order_item_coupon oic
            LEFT JOIN mall_order.order_item oi ON oic.item_id = oi.item_id
        WHERE
            oi.order_id = {orderId}
        """
    # print(f"将要执行的sql是： {selectOrderItemDiscountsSql}" )
    cursor.execute(selectOrderItemDiscountsSql)
    items = cursor.fetchall()
    oids = []
    for item in items:
        oi = OrderItemDiscount(item[0], item[1], item[2], item[3], item[4], item[5], item[6], item[7])
        oids.append(oi.__dict__)
    return oids


def getOrderItemListByOrderSn(orderId):
    # 参数校验
    isPass = _checkParams(orderId)
    if not isPass:
        print("参数校验不通过，程序自动退出")
        return
    # 准备基本参数
    # 使用 cursor() 方法创建一个游标对象 cursor
    db = pymysql.connect("db1.dev1.yiyao.cc", "mall_root", "20151118", "mall_order", port=13306, charset='utf8')
    cursor = db.cursor()

    # 获取医药订单list信息
    orderItemList = _getOrderItemList(cursor, orderId)
    if not orderItemList:
        print("查询到的医药订单商品信息为空，程序自动退出")
        return
    orderItemListJson = json.dumps(orderItemList, ensure_ascii=False)
    print(orderItemListJson)

    orderItemDiscountList = _getOrderItemDiscountList(cursor, orderId)
    if not orderItemList:
        print("查询到的医药订单优惠信息为空，程序自动退出")
        return
    orderItemDiscountListJson = json.dumps(orderItemDiscountList, ensure_ascii=False)
    print(orderItemDiscountListJson)

    try:
        pass
        # print("全部执行完成，将要提交事务")
    except Exception as e:
        traceback.print_exc()
        print(e)
        # 发生错误时回滚
        print("发生错误，事务回滚")
        db.rollback()
    finally:
        # 关闭数据库连接
        db.close()
    print("查询成功")


class OrderItem:
    def __init__(self, orderId, itemId, itemName, count, price, discountPrice, residuePrice, finalPrice, finalCount,
                 finalStatus, status):
        self.orderId = orderId
        self.itemId = itemId
        self.itemName = itemName
        self.count = count
        self.price = price
        self.discountPrice = discountPrice
        self.residuePrice = residuePrice
        self.finalPrice = finalPrice
        self.finalCount = finalCount
        self.finalStatus = finalStatus
        self.status = status

    def __str__(self) -> str:
        return super().__str__()


class OrderItemDiscount():
    def __init__(self, orderId, orderCount, deliveryCount, discountType, itemId, discountId, shareDiscountAmount,
                 costHolder):
        self.orderId = orderId
        self.orderCount = orderCount
        self.deliveryCount = deliveryCount
        self.discountType = discountType
        self.itemId = itemId
        self.discountId = discountId
        self.shareDiscountAmount = shareDiscountAmount
        self.costHolder = costHolder

    def __str__(self) -> str:
        return super().__str__()


if __name__ == "__main__":
    orderId = '1161072'
    getOrderItemListByOrderSn(orderId)
